package com.groupbuying.task.controller;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.google.common.base.Strings;
import com.groupbuying.task.mq.StoreInternalMQConfig;
import com.groupbuying.task.mq.StoreInternalMQProductor;
import com.groupbuying.task.mq.StoreMQProductor;
import com.groupbuying.task.utils.DateFormatHelper;
import com.groupbuying.task.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zmlmagic
 * @date 2019/10/8 11:58 AM
 * @company 蒙泰互联网公司
 * @des store定时任务接口
 **/
@RequestMapping("/store")
@RestController
public class StoreTaskController {
    private static final Logger logger = LoggerFactory.getLogger(StoreTaskController.class);

    @Autowired
    private StoreInternalMQProductor storeInternalMQProductor;

    @Value("${task.scheduled.store.rule:false}")
    private String isSetRule;

    @Value("${taskAccessToken:}")
    private String taskAccessToken;

    //创建，更新定时任务
    @GetMapping("/updateRule")
    public Boolean updateRule(@RequestParam Map<String, Object> params) {
        String accessToken = params.get("accessToken").toString();

        if(!isSetRule.equals("true") || Strings.isNullOrEmpty(accessToken) ||!accessToken.equals(taskAccessToken)){
            logger.info("非法访问");
            return false;
        }

        Producer producer = storeInternalMQProductor.getStoreMQProductor();
        try {
            Map map = new HashMap();
            map.put("timeStamp",System.currentTimeMillis());
            Message message = new Message(StoreInternalMQConfig.TOPIC, StoreInternalMQConfig.UPDATERULE, JSONUtils.beanToJson(map).getBytes());
            producer.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        logger.info(DateFormatHelper.getNowTimeStr()+"=========开始执行定时任务-->更新商户每日运营规则==========");
        // 3.添加定时任务
        return true;
    }
}
